package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"shopstar/config"
)

var DB *gorm.DB

// DSN mysql连接拼接 username:password@tcp(host:port)/dbname?charset=utf8mb4
const DSN = "%s:%s@tcp(%s:%d)/%s?charset=%s"

func InitDb(config *config.Config) {
	var err error
	username := config.Mysql.Username
	password := config.Mysql.Password
	host := config.Mysql.Host
	port := config.Mysql.Port
	dbname := config.Mysql.Dbname
	charset := config.Mysql.Charset

	dsn := fmt.Sprintf(DSN, username, password, host, port, dbname, charset)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) //如果表有前缀，可以在&gorm.Config{}里面设置
	if err != nil {
		panic(fmt.Errorf("models/db.go:InitDb Fatal error mysql connect : %s \n", err))
	}
	initWuid(dsn)
}
